<template>
  <div>
    <div class="h-[64px] flex items-center gap-[24px] px-[24px] border-b border-[#E1E2E3]">
      <svg
        xmlns="http://www.w3.org/2000/svg"
        width="32"
        height="32"
        viewBox="0 0 32 32"
        class="cursor-pointer"
        @click="goBack"
        fill="none">
        <path
          fill-rule="evenodd"
          clip-rule="evenodd"
          d="M11.2933 8.89258C11.6838 8.50247 12.3169 8.50224 12.7073 8.89258C13.0975 9.28299 13.0974 9.91615 12.7073 10.3066L8.01298 15H20.5032L20.6048 15.0049C21.1092 15.0559 21.5032 15.4821 21.5032 16C21.5031 16.5178 21.1091 16.9441 20.6048 16.9951L20.5032 17H8.01494L12.7073 21.6924C13.0976 22.0828 13.0973 22.7159 12.7073 23.1064C12.3168 23.4969 11.6838 23.4969 11.2933 23.1064L4.89287 16.707C4.50246 16.3166 4.50256 15.6835 4.89287 15.293L11.2933 8.89258ZM25.5999 8.59961C26.1521 8.59961 26.5998 9.0474 26.5999 9.59961V22.3994C26.5999 22.9517 26.1522 23.3994 25.5999 23.3994C25.0477 23.3994 24.5999 22.9517 24.5999 22.3994V9.59961C24.6 9.04744 25.0477 8.59967 25.5999 8.59961Z"
          fill="#222222" />
      </svg>
      <svg xmlns="http://www.w3.org/2000/svg" width="2" height="34" viewBox="0 0 2 34" fill="none">
        <path d="M1 1V33" stroke="#E1E2E3" stroke-width="0.5" stroke-linecap="round" />
      </svg>
      <span class="title_text">{{ route.query.title || '3D Photo' }}</span>
    </div>

    <div class="flex h-[calc(100vh-64px)]">
      <div class="p-[24px] w-[560px] bg-[#fff]">
        <div class="text-[#222] text-[16px] font-bold mb-[8px]">Reference Image</div>
        <ImageUploader v-model="formData.url" />
        <div class="generate-button" :class="{ loading: isGenerating }" @click="handleGenerate">
          <span v-if="!isGenerating">Generate Now</span>
          <span v-else class="flex items-center justify-center gap-2">
            <svg
              class="animate-spin h-4 w-4"
              xmlns="http://www.w3.org/2000/svg"
              fill="none"
              viewBox="0 0 24 24">
              <circle
                class="opacity-25"
                cx="12"
                cy="12"
                r="10"
                stroke="currentColor"
                stroke-width="4"></circle>
              <path
                class="opacity-75"
                fill="currentColor"
                d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
            </svg>
            Generating...
          </span>
        </div>
      </div>
      <!-- 右侧 -->
      <div class="flex-1 bg-[#F8F8F8] px-[40px] py-[16px] overflow-y-auto">
        <div class="flex items-center justify-between mb-[8px]">
          <div class="text-[#222] text-[16px] font-bold">Results</div>
        </div>
        <div class="flex flex-col mt-[24px]">
          <!-- 加载状态 -->
          <div v-if="isLoadingResults" class="text-center text-gray-500 py-20">
            <svg
              class="animate-spin h-8 w-8 mx-auto mb-4"
              xmlns="http://www.w3.org/2000/svg"
              fill="none"
              viewBox="0 0 24 24">
              <circle
                class="opacity-25"
                cx="12"
                cy="12"
                r="10"
                stroke="currentColor"
                stroke-width="4"></circle>
              <path
                class="opacity-75"
                fill="currentColor"
                d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
            </svg>
            Loading...
          </div>

          <!-- 显示生成结果 -->
          <div
            v-else-if="generateResults.length > 0"
            v-for="result in generateResults"
            :key="result.id"
            class="mb-[40px]">
            <div class="flex">
              <div
                class="text-[#222] text-[14px] mb-[16px] bg-[#EDEDED] rounded-[8px] px-[12px] py-[8px]">
                {{ result.created_at }}
              </div>
            </div>
            <!-- 一行4个图片，间距24px -->
            <div class="grid grid-cols-4 gap-[24px]">
              <!-- 已有结果 -->
              <div
                class="aspect-square bg-white rounded-[8px] overflow-hidden relative group cursor-pointer"
                v-for="(image, index) in result.result_imgs"
                :key="index">
                <el-skeleton
                  v-if="image.status === 0"
                  width="100%"
                  height="100%"
                  style="aspect-ratio: 1"
                  class="image-skeleton"
                  :animated="true">
                  <template #template>
                    <el-skeleton-item variant="image" style="width: 100%; height: 100%" />
                  </template>
                </el-skeleton>

                <!-- 已生成 -->
                <div v-else class="w-full h-full">
                  <img :src="image.img_url" alt="result" class="w-full h-full object-cover" />
                  <div
                    class="absolute bottom-[16px] flex justify-center w-full opacity-0 group-hover:opacity-100 transition-opacity duration-300">
                    <div class="buy-now-button" @click="goBuyNow(result, image.img_id)">
                      Buy Now
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <!-- 如果没有生成结果，显示占位内容 -->
          <div v-else-if="generateResults.length === 0" class="text-center text-gray-500 py-20">
            <NoData :title="getTitle()" :size="128" />
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
  import ImageUploader from '@/components/ImageUploader.vue';
  import NoData from '@/components/NoData.vue';
  import { ref, onMounted, onUnmounted, computed, watch } from 'vue';
  import { AiAPI } from '@/api/ai';
  import { PayAPI } from '@/api/pay';
  import { useOrderStore } from '@/store/order';
  import { ElMessage } from 'element-plus';
  import { useRouter, useRoute } from 'vue-router';
  import { OrderType } from '@/api/nex';
  import { useUserStore } from '@/store/user';
  const router = useRouter();
  const route = useRoute();
  const orderStore = useOrderStore();

  const userStore = useUserStore();
  const isLoggedIn = computed(() => userStore.isAuthenticated);

  // 表单数据模型
  const formData = ref({
    template_id: 0,
    prompt: '',
    url: '', // 用于存储上传后的图片URL
  });

  // Loading状态
  const isGenerating = ref(false);
  const isLoadingResults = ref(false);
  const processingStatus = ref(0);

  // 生成结果列表
  const generateResults = ref<any[]>([]);

  const getTitle = () => {
    return `First upload your photo in the left section, then click the "Generate
            Now" button, and wait for the result to load`;
  };

  const goBuyNow = async (info: any, img_id: string) => {
    const params = {
      product_id: route.query.product_id,
      quality: 1,
      pay_method: 1,
      variant_id: info.gen_template.third_product_id,
      order_type: OrderType.POD,
      img_id: img_id,
    };
    orderStore.createOrderHandle(params);
  };

  // 返回上一页
  const goBack = () => {
    router.back();
  };

  // 获取生成结果
  const fetchGenerateResults = async (needLoading: boolean = true) => {
    try {
      if (needLoading) {
        isLoadingResults.value = true;
      }
      const response = await AiAPI.generateProductResult({
        product_id: route.query.product_id as any,
        gen_type: 2,
      });
      response.data.forEach((element: any) => {
        if (!element.result_imgs.length) {
          // 没返回结果，先显示骨架图
          element.result_imgs = [1, 2, 3, 4].map((cItem: any, index: number) => {
            return {
              status: 0,
            };
          });
        }
      });
      generateResults.value = response.data;
    } catch (error) {
      console.error('获取生成结果失败:', error);
    } finally {
      isLoadingResults.value = false;
    }
  };

  // 轮询定时器
  let pollingTimer: NodeJS.Timeout | null = null;

  // 检查进行中的任务
  const checkInProgressTasks = async () => {
    try {
      const response = await AiAPI.inProgressTasks({ product_type: 2 });
      const inProgressTasks = response.data || [];
      processingStatus.value = inProgressTasks.length;
      return inProgressTasks.length > 0; // 返回是否有进行中的任务
    } catch (error) {
      console.error('检查进行中任务失败:', error);
      return false;
    }
  };

  // 开始轮询
  const startPolling = async () => {
    // 立即检查一次
    const hasInProgress = await checkInProgressTasks();

    if (!hasInProgress) {
      // 没有进行中的任务，直接获取结果
      await fetchGenerateResults(true);
      return;
    }

    // 有进行中的任务，开始轮询
    pollingTimer = setInterval(async () => {
      const hasInProgress = await checkInProgressTasks();

      if (!hasInProgress) {
        // 没有进行中的任务了，停止轮询并获取结果
        if (pollingTimer) {
          clearInterval(pollingTimer);
          pollingTimer = null;
        }
        await fetchGenerateResults(false);
      }
    }, 3000); // 每3秒检查一次
  };

  // 停止轮询
  const stopPolling = () => {
    if (pollingTimer) {
      clearInterval(pollingTimer);
      pollingTimer = null;
    }
  };

  // 生成按钮点击处理
  const handleGenerate = async () => {
    if (isGenerating.value) return;

    // 验证必填字段
    if (!formData.value.url) {
      ElMessage.warning('Please upload the picture.');
      return;
    }

    try {
      isGenerating.value = true;

      // 调用生成产品接口
      const response = await AiAPI.generateProduct({
        gen_type: 2, // 固定值传2
        template_id: route.query.template_id as any, // 使用表单中的template_id，默认为10
        img: formData.value.url, // 使用上传的图片URL
        product_id: route.query.product_id as any,
      });

      fetchGenerateResults(false);

      // 生成完成后，开始轮询检查进行中的任务
      await startPolling();
    } catch (error) {
      console.error('生成失败:', error);
    } finally {
      isGenerating.value = false;
    }
  };

  // 监听用户登录状态变化
  watch(isLoggedIn, (newValue, oldValue) => {
    if (newValue) {
      fetchGenerateResults(true);
    }
  });

  // 组件挂载时检查是否有进行中的任务
  onMounted(async () => {
    if (isLoggedIn.value) {
      await startPolling();
    }
  });

  // 组件卸载时清理轮询
  onUnmounted(() => {
    stopPolling();
  });
</script>

<style scoped lang="scss">
  .generate-button {
    border-radius: 8px;
    background: var(---, linear-gradient(90deg, #f76b1b 0%, #dc3a0e 100%));
    backdrop-filter: blur(2px);
    color: #fff;
    font-size: 18px;
    font-style: normal;
    font-weight: 500;
    padding: 12px 24px;
    text-align: center;
    cursor: pointer;
    margin-top: 38px;
    transition: all 0.3s ease;

    &:hover:not(.loading) {
      transform: translateY(-2px);
      box-shadow: 0 4px 12px rgba(247, 107, 27, 0.3);
    }

    &.loading {
      cursor: not-allowed;
      opacity: 0.8;
    }
  }
  .buy-now-button {
    border-radius: 28px;
    background: var(---, linear-gradient(90deg, #f76b1b 0%, #dc3a0e 100%));
    backdrop-filter: blur(2px);
    color: #fff;
    font-size: 14px;
    font-style: normal;
    font-weight: 500;
    text-align: center;
    width: 60%;
    padding: 2px 0;
    cursor: pointer;
    transition: all 0.3s ease;

    &:hover {
      transform: scale(1.05);
      box-shadow: 0 2px 8px rgba(247, 107, 27, 0.4);
    }
  }
  .title_text {
    font-size: 16px;
    font-weight: 600;
  }
</style>
